namespace SimpleTPL;

using System;
using System.Runtime.CompilerServices;

public struct SimpleAsyncMethodBuilder
{
    private SimpleTask _task;
    private Exception _exception;

    public static SimpleAsyncMethodBuilder Create() => new SimpleAsyncMethodBuilder();

    public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
    {
        // 使用本地变量捕获状态机
        var boxedStateMachine = (IAsyncStateMachine)stateMachine;
        var task = _task = new SimpleTask(() => boxedStateMachine.MoveNext());
        SimpleThreadPool.UnsafeQueueUserWorkItem(_ => {
            boxedStateMachine.MoveNext();
            task.Execute();
        });
    }

    public void SetException(Exception exception)
    {
        _exception = exception;
        _task?.SetException(exception);
    }

    public void SetResult()
    {
        _task?.SetResult();
    }

    public void AwaitOnCompleted<TAwaiter, TStateMachine>(
        ref TAwaiter awaiter, TStateMachine stateMachine)
        where TAwaiter : INotifyCompletion
        where TStateMachine : IAsyncStateMachine
    {
        awaiter.OnCompleted(stateMachine.MoveNext);
    }

    public SimpleTask Task => _task ??= new SimpleTask(() => {});
}